/**
 * Created by JLB1 on 2017/2/7.
 */

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Clipboard from 'clipboard';
import AJAX from '../../lib/ajax';
import Tools from '../../lib/tools';
import Dialog from "../MyPackage/components/Dialog";
import wx from 'wx';
import { addErrorListener } from '../../lib/handleError';

require('../../styles/common.less');
require('../../styles/lux.less');
require('./NewPickUpDetail.less');

class NewPickUpDetail extends Component {
    constructor(props) {
        super(props);
        this.state = {
            order_id: Tools.getParams().order_id,
            order_type: +Tools.getParams().order_type,   // TODO: 3:柜体 ; 4: 暂存区;
            orderDetail: null,
            unpickCount: 0,
            prepay_data: null,
            isCheck: Tools.getParams().isCheck,
            manageName: '',

            confirmCabinetDialog: false,
        };
    }

    componentWillMount() {
        addErrorListener()();

        const id = Tools.getParams().order_id;
        const aditem_id = Tools.getParams().aditem_id;

        if (+aditem_id) {
            // 统计点击
            AJAX.request('advertSave', { advertId: aditem_id, type: 2 }, (res) => {
                const { code } = res;
                if (code === 0) {
                    AJAX.request("get_advert_url", { advert_id: aditem_id, action: 1 }, (data) => {
                        if (data.body.url) {
                            window.location.replace(data.body.url);
                        }
                        else {
                            //跳转首页
                            const wx_type = window.localStorage.getItem('wx_type');
                            window.location.href = `./PickUp?wx_type=${wx_type}`;
                        }
                    })
                }
            });

        } else {
            //获取详情
            AJAX.request('new_order_info', { orderId: id, }, data => {
                if (data.code == 0) {
                    this.setState({
                        orderDetail: data.body,
                        unpickCount: Tools.getParams().count || 1,
                    });
                }
            });
        }
    }

    componentDidMount() {
        const aditem_id = Tools.getParams().aditem_id;
        const manageNameInSession = sessionStorage.getItem('manageData');
        //  客户管理-根据手机号查询
        if (!aditem_id && !manageNameInSession) {
            AJAX.request('queryByPhone', {}, data => {
                if (data.body.id > 0) {
                    sessionStorage.setItem('manageData', JSON.stringify(data.body));
                }
            });
        }

        new Clipboard('.right-btn');
        new Clipboard('.icon-copy');
        AJAX.appendBaiduAnalysis();
    }

    /**
     * 
     * @param {*} id 
     * 新驿站 一键开箱 
     */
    handleNewPickup = (order) => {
        const { isCheck } = this.state;

        if (order.isScanCode === 1 && !isCheck) {
            this.setState({ confirmCabinetDialog: true });
        } else {
            // 订单收费时，走支付流程
            if (order.pickupAmount > 0 && order.isPaid === 0) {
                this.getPrePay(order.orderId);
            }
            else {
                Dialog.confirm({
                    title: '',
                    content: '检测到您当前位置与柜体距离较远！请核对您的位置与柜体位置是否一致，否则由此带来的损失由您负责。',
                    okText: '仍要开箱',
                    cancelText: '取消',
                    onOK: () => {
                        window.location.href = `./OpenBoxNewFinal?order_id=${order.orderId}`;
                    },
                });
            }
        }
    }

    /**
     * 新驿站确认取件
     */
    handleNewSelfPickup = (order) => {

        const that = this;
        Dialog.confirm({
            title: '提示',
            htmlContent: (<div style={{ padding: '15px' }}>
                <div style={{ color: '#999', marginBottom: '10px' }}>请确认是否已取走</div>
                <div style={{ color: 'red' }}>注意: 确认取走后，该包裹视为本人取走。</div>
            </div>),
            okText: '确认',
            cancelText: '取消',
            onOK: () => {
                // 自助取件
                AJAX.request('new_pickUp', { orderId: order.orderId, stationId: order.stationId }, result => {
                    if (!result.body.to_pickup_count || result.body.to_pickup_count < 1) {
                        AJAX.request('get_advert_detail', { type: 6 }, (data) => {
                            that.fetchSaveAdvert(data.body.id, 4);
                            if (data.code == 0) {
                                var advert_url = data.body.url;
                                window.location.href = advert_url;
                            }
                        })
                    } else {
                        const wx_type = window.localStorage.getItem('wx_type');
                        window.location.href = `./PickUp?wx_type=${wx_type}`;   //返回首页
                    }
                });
            },
        })
    }

    /**
     * 
     * @param {*} advertId 广告id
     * @param {*} type 2: 点击; 3: 曝光; 4: 跳转;
     */
    fetchSaveAdvert(advertId, type) {
        const params = {
            advertId: advertId,
            type: type,
        };
        AJAX.request('advertSave', params, (data) => {
            const { code, body } = data;
            if (code === 0) {
                console.log('记录成功', body);
            }
        });
    }

    // 获取wx支付所需要的参数
    getPrePay = (orderId) => {
        const params = {
            stype: 'weixin_user',
            order_id: orderId,
        };
        AJAX.request("create_trade_prepay", params, data => {
            const prepay_data = data.body.prepay
            this.setState({
                prepay_data,
                amount: data.body.total_fee / 100,
            }, () => {
                this.pay();
            })
        })
    }

    handleConfirmCabinet = e => {
        e.stopPropagation();

        const { orderDetail } = this.state;

        window.location.href = `./ConfirmCabinet?order_id=${orderDetail.orderId}&cabinet_code=${orderDetail.cabinetCode}&listType=new_unpick`;
    }

    createConfirmCabinetDialogElem = () => (
        <div
            className="dialog-confirm"
            onClick={this.hideConfirmCabinetDialog}
        >
            <div className="dialog-box">
                <div className="dialog-content">
                    <div className="title">安全提示</div>
                    <div className="desc">为了您的包裹安全，请扫描柜体条码取件</div>
                    <img src="https://cdn2.jinlb.cn/pic/fd/14/fd1414a22495532596caa354efbd510f.png" />
                </div>
                <div
                    className="dialog-footer"
                    onClick={this.handleConfirmCabinet.bind(this)}
                >
                    扫描
                </div>
            </div>
        </div>
    )

    /**
     * 
     * @param {*} id stationId
     * @param {*} success 点确定后成功回调
     */
    whiteManageName = (id, success) => {
        Dialog.confirm({
            title: '提示',
            htmlContent: (
                <div style={{ padding: '0 20px', margin: '15px 0' }}>
                    <div className="weui-cell weui-cell_active" style={{ border: '1px solid #cdcdcd' }}>
                        {/* <div className="weui-cell__hd"><span className="weui-label">快递单号/取件码</span></div> */}
                        <div className="weui-cell__bd weui-flex">
                            <input className="weui-input" type="text" maxLength={30} placeholder={"请输入收件人购物昵称"} onChange={(e) => {
                                this.setState({ manageName: e.target.value });
                            }} />
                        </div>
                    </div>
                    <div style={{ margin: '15px 0', textAlign: 'left', color: 'red' }}>提示: 为了您能及时收到取件通知,请准确填写收件人购物昵称</div>
                </div>
            ),
            content: '',
            okText: '下一步',
            cancelText: '取消',
            onOK: () => {
                const { manageName } = this.state;
                AJAX.request('manageRegister', {
                    name: manageName,
                    stationId: id,
                }, data => {
                    if (data.code === 0) {
                        sessionStorage.setItem('manageData', JSON.stringify({ name: manageName, stationId: id }));
                        success();
                    }
                });
            },
        })
    };

    pay() {
        const { prepay_data, order_id } = this.state
        AJAX.request('get_signature', {
            full_url: window.location.href
        }, (data) => {

            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: data.body.appid, // 必填，公众号的唯一标识
                timestamp: data.body.timestamp, // 必填，生成签名的时间戳
                nonceStr: data.body.noncestr, // 必填，生成签名的随机串
                signature: data.body.signature,// 必填，签名，见附录1
                jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
            })
            wx.ready(() => {
                wx.chooseWXPay({
                    timestamp: prepay_data.timeStamp, // 签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                    nonceStr: prepay_data.nonceStr, // 支付签名随机串，不长于 32 位
                    package: prepay_data.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
                    signType: prepay_data.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                    paySign: prepay_data.paySign, // 支付签名
                    success: (res) => {
                        setTimeout(() => {
                            window.location.href = `./OpenBoxNewFinal?order_id=${order_id}`;
                        }, 1000)
                    },
                    fail: (res) => {
                        alert('支付失败')
                    }
                })
            })
        })

    }

    render() {
        const { orderDetail, unpickCount, order_type, confirmCabinetDialog } = this.state;

        return (
            orderDetail && (<div>
                <div className="header stationInfo">
                    <div>{order_type === 3 ? orderDetail.addr : orderDetail.address}</div>
                    <div className="serverPhone">
                        <img className="phoneIcon" src="//wechat.jinlb.cn/assets/images/detail-phone.png" />
                        <div>服务电话: {orderDetail.servicePhone}</div>
                        <a href={`tel:${orderDetail.servicePhone}`}><img className="telIcon" src="//wechat.jinlb.cn/assets/images/phone.png" /></a>
                    </div>
                    <div className="pickCode">
                        <div>取件码: {orderDetail.pickupCode}</div>
                        {unpickCount > 1 && <div className="unpick-count">
                            另有{unpickCount - 1}件包裹
                        </div>}
                    </div>
                </div>

                <div className="expressDetail">
                    <div className="expressCard">
                        <div className="lux-d-f expressInfo">
                            <div className="lux-d-f">
                                <img className="expressIcon" src={orderDetail.expLogo} />
                                <div className="lux-fz16 lux-c333 lux-fw-b wordOmit">{orderDetail.expName} {orderDetail.expCode}</div>
                                <img className="copyIcon" src="//wechat.jinlb.cn/assets/images/detail-copy.png" onClick={() => {
                                    Tools.copyExpCode(orderDetail.expCode);
                                }} />
                            </div>
                            <div className="time">{orderDetail.operLogInfo[orderDetail.operLogInfo.length - 1].createTime}</div>
                        </div>
                        {order_type === 3 ? (
                            // 柜体件
                            <div className="express">
                                {orderDetail.isFree !== 2 && <div className="expressItem">取件应收: {orderDetail.pickupAmount / 100}元</div>}
                                <div className="expressItem">柜体编号: {orderDetail.cabinetCode}</div>
                                <div className="cabinet">
                                    <div className="cell-desc">
                                        <div>
                                            <div>您的快递在格口:</div>
                                            <div style={{ fontSize: 46 }}>{orderDetail.cellCodeDesc}</div>
                                        </div>
                                    </div>
                                    <div className="cell-img">
                                        <img src={"//wechat.jinlb.cn/assets/images/cabinet-loading.png"} />
                                    </div>
                                </div>
                                {orderDetail.status === 2 && <div className="button-box lux-d-f lux-ai-c">
                                    <div className="lux-flex-1 lux-center">
                                        <div
                                            className={'right-btn button2'}
                                            style={{ fontSize: 18, flex: 1, height: 42 }}
                                            onClick={(e) => {
                                                e.stopPropagation();
                                                const callback = () => {
                                                    this.handleNewPickup(orderDetail)
                                                }
                                                const manageNameInSession = sessionStorage.getItem('manageData');
                                                if (!manageNameInSession) {
                                                    this.whiteManageName(orderDetail.stationId, callback);
                                                }
                                                else {
                                                    this.handleNewPickup(orderDetail)
                                                }

                                            }}
                                        >
                                            {orderDetail.pickupAmount > 0 && orderDetail.isPaid === 0 ? '支付并开箱' : '一键开箱'}
                                        </div>
                                    </div>
                                </div>}
                            </div>
                        ) : order_type === 4 ? (
                            <div className="express">
                                <div className="expressItem">取件应收: {orderDetail.pickupAmount / 100}元</div>
                                {orderDetail.status === 2 && <div className="contact">
                                    请联系门店人员取件!
                                </div>}
                            </div>
                        ) : (<div className="express">
                            <div className="expressItem">取件应收: {orderDetail.pickupAmount / 100}元</div>
                            <div className="expressItem">到付应收: {orderDetail.arriveAmount / 100}元</div>
                            <div className="expressItem">总费用: {(orderDetail.pickupAmount + orderDetail.arriveAmount) / 100}元</div>
                            {orderDetail.status === 2 && orderDetail.isStationPickup === 1 && !((orderDetail.pickupAmount + orderDetail.arriveAmount) > 0 && orderDetail.isPaid === 0) && <div className="button-box lux-d-f lux-ai-c">
                                <div className="lux-flex-1 lux-center">
                                    <div
                                        className={'right-btn button2'}
                                        style={{ fontSize: 18, flex: 1, height: 42 }}
                                        onClick={(e) => {
                                            e.stopPropagation();
                                            const callback = () => {
                                                this.handleNewSelfPickup(orderDetail)
                                            }
                                            const manageNameInSession = sessionStorage.getItem('manageData');
                                            if (!manageNameInSession) {
                                                this.whiteManageName(orderDetail.stationId, callback);
                                            }
                                            else {
                                                this.handleNewSelfPickup(orderDetail)
                                            }
                                        }}
                                    >
                                        确认取走
                                    </div>
                                </div>
                            </div>}
                        </div>)}
                    </div>
                </div>

                {confirmCabinetDialog && this.createConfirmCabinetDialogElem()}
            </div >)
        );
    }

}

ReactDOM.render(<NewPickUpDetail />, document.getElementById('app'));

if (module.hot) {
    module.hot.accept();
}